const { Service } = require('egg')
const Response = require('../utils/Response')
const permissionAll = require('../utils/constant')

class publicService extends Service {
  // 获取课程name与id列表
  async queryCurList() {
    const { mysql } = this.app
    const result = await mysql.query('SELECT cur_code, cur_name FROM curriculum')
    if (result.length) {
      return result
    } else {
      return []
    }
  }

  // h获取教师信息列表
  async queryTeaList() {
    const { mysql } = this.app
    const result = await mysql.query('SELECT tea_code, tea_name FROM teachers')
    if (result.length) {
      return result
    } else {
      return []
    }
  }

  // 获取周次列表信息
  async queryWeeklyList() {
    const { mysql } = this.app
    const result = await mysql.query('SELECT * FROM weekly')
    if (result.length) {
      return result
    } else {
      return []
    }
  }

  // 获取教室信息列表
  async queryClassRoomList() {
    const { mysql } = this.app
    const result = await mysql.query('SELECT id, class_room FROM class_room')
    if (result.length) {
      return result
    } else {
      return []
    }
  }

  // 获取每天上课时间列表
  async queryDayTimeList() {
    const { mysql } = this.app
    const result = await mysql.query('SELECT * FROM time')
    return result
  }

  // 获取现在已经排课的课程
  async queryPlanCourses() {
    const { ctx } = this
    const { mysql } = this.app
    const sql = `SELECT teacher_id, teachers.tea_name as tea_name, curriculum.cur_name as cur_name, curriculum.cur_type as cur_type, curriculum.cur_price as cur_price, course_id
        FROM time_table JOIN curriculum ON time_table.course_id = curriculum.cur_code
        JOIN teachers ON time_table.teacher_id = teachers.tea_code
        WHERE curriculum.cur_statusCode = ?`
    try {
      const result = await mysql.query(sql, ['1'])
      let uniqueArr = []
      result.forEach((item) => {
        !uniqueArr.some((ite) => ite.course_id === item.course_id) && uniqueArr.push({ ...item })
      })
      ctx.body = new Response('查询成功', 200, uniqueArr)
    } catch (err) {
      throw new Response('error', 500, err)
    }
  }

  // 获取所有学生信息
  async queryAllStudent(params) {
    const { ctx } = this
    const { mysql } = this.app
    const offSet = params.page === '1' ? 0 : (Number(params.page) - 1) * Number(params.pageSize)
    const pageSize = Number(params.pageSize)
    const name = params?.name ? params.name : null
    try {
      const total = await mysql.query(
        `SELECT COUNT(*) as cnt FROM students WHERE (stu_name LIKE CONCAT ('%', ?, '%') OR ? IS NULL) LIMIT ? OFFSET ?`,
        [name, name, pageSize, offSet]
      )
      const result = await mysql.query(
        `SELECT * FROM students WHERE (stu_name LIKE CONCAT ('%', ?, '%') OR ? IS NULL) LIMIT ? OFFSET ?`,
        [name, name, pageSize, offSet]
      )
      ctx.body = new Response('查询成功', 200, { total: total[0].cnt, list: result })
    } catch (err) {
      throw new Response('查询失败', 500, err)
    }
  }

  // 学生列表下拉
  async queryStuSelect() {
    const { ctx } = this
    const { mysql } = this.app
    try {
      const result = await mysql.query(`SELECT stu_code, stu_name, stu_gender FROM students`)
      ctx.body = new Response('查询成功', 200, result)
    } catch (err) {
      throw new Response('err', 500, err)
    }
  }

  // 获取动态路由
  async getRouter(params) {
    const { ctx } = this
    const { mysql } = this.app
    const sql = `SELECT roles FROM roles WHERE id=?`
    try {
      let roleList = await mysql.query(sql, [params.id])
      roleList = JSON.parse(roleList[0].roles)
      /**
       * 遍历原始路由与现有权限路由对比，删除原始路由中没有的权限路由
       */
      let permissionList = JSON.parse(JSON.stringify(permissionAll))
      permissionList.forEach((item) => {
        if (!item?.children) return
        item.children = item.children.filter((child) => roleList.includes(child.name))
      })
      permissionList.forEach((item) => {
        if (!item?.children) return
        !item.children.length && (item.meta.hide = true)
      })
      ctx.body = new Response('success', 200, permissionList)
    } catch (err) {
      throw new Response('异常错误', 500, err)
    }
  }

  // 获取当前登录用户信息
  async getUserInfo(params) {
    const { ctx } = this
    const { mysql } = this.app
    const sql = `SELECT * FROM teachers WHERE tea_code=?`
    const result = await mysql.query(sql, [params.tea_code])
    ctx.body = new Response('success', 200, result[0])
  }

  // 更新用户信息
  async updateInfo(params) {
    const { ctx } = this
    const { mysql } = this.app
    const sql = `UPDATE teachers SET email=?, gender=?, age=?, tel=? WHERE tea_code=?`
    const { email, gender, age, tel, tea_code } = params
    const result = await mysql.query(sql, [email, gender, age, tel, tea_code])
    ctx.body = result.affectedRows === 1 ? new Response('更新成功', 200) : new Response('更新失败', 500)
  }

  // 修改当前登录用户密码
  async editPass() {
    const { ctx } = this
    const { mysql } = this.app
  }

  // 更新登录用户密码
  async updatePass() {
    const { ctx } = this
    const { mysql } = this.app
    const sql = ``
  }

  // 学员总数
  async studentNum() {
    const { ctx } = this
    const { mysql } = this.app
    const sql = `SELECT COUNT(*) as cnt FROM students`
    const result = await mysql.query(sql)
    ctx.body = new Response('success', 200, result[0].cnt)
  }

  // 教师总数
  async teacherNum() {
    const { ctx } = this
    const { mysql } = this.app
    const sql = `SELECT COUNT(*) as cnt FROM teachers`
    const result = await mysql.query(sql)
    ctx.body = new Response('success', 200, result[0].cnt)
  }

  // 课程数
  async courseNum() {
    const { ctx } = this
    const { mysql } = this.app
    const sql = `SELECT COUNT(*) as cnt FROM time_table`
    const result = await mysql.query(sql)
    ctx.body = new Response('success', 200, result[0].cnt)
  }

  // 订单数
  async orderNum() {
    const { ctx } = this
    const { mysql } = this.app
    const sql = `SELECT COUNT(*) as cnt FROM orders`
    const result = await mysql.query(sql)
    ctx.body = new Response('success', 200, result[0].cnt)
  }
}

module.exports = publicService
